package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    public TurnoverReportVO getTurnoverStatistics(LocalDate startDate, LocalDate endDate){
        List<LocalDate> dateList = getLocalDateList(startDate, endDate);
        List<Double> turnoverList = new ArrayList<>();

        for(LocalDate date : dateList){
            LocalDateTime begin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime end = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", begin);
            map.put("end", end);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            if(turnover == null){ turnover = 0.0; }
            turnoverList.add(turnover);
        }

        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
        return turnoverReportVO;
    }


    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = getLocalDateList(begin, end);
        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();

        LocalDateTime beginDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        Integer last = userMapper.countByDate(beginDateTime);

        for(LocalDate date : dateList){
            LocalDateTime endDateTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer newTotalUser = userMapper.countByDate(endDateTime);
            log.info(String.valueOf(newTotalUser));
            newUserList.add(newTotalUser-last);
            totalUserList.add(newTotalUser);
            last = newTotalUser;
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .newUserList(StringUtils.join(newUserList,","))
                .totalUserList(StringUtils.join(totalUserList,","))
                .build();
    }

    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = getLocalDateList(begin, end);
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for(LocalDate date : dateList){
            LocalDateTime beginDateTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endDateTime = LocalDateTime.of(date, LocalTime.MAX);
            Integer orderCount = getOrderCount(beginDateTime,endDateTime,null);
            Integer validOrderCount = getOrderCount(beginDateTime,endDateTime,Orders.COMPLETED);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        Integer validTotalOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        Double orderCompletionRate = 0.0;
        if(totalOrderCount > 0){
            orderCompletionRate = validTotalOrderCount / (double)totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validTotalOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();

    }

    private Integer getOrderCount(LocalDateTime begin, LocalDateTime end,Integer status){
        Map map = new HashMap();
        map.put("begin", begin);
        map.put("end", end);
        map.put("status", status);
        return orderMapper.countByMap(map);

    }

    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end){
        LocalDateTime beginDateTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endDateTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginDateTime,endDateTime);
        List<String> names = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numbers = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(names,","))
                .numberList(StringUtils.join(numbers,","))
                .build();
    }


    private List<LocalDate> getLocalDateList(LocalDate startDate, LocalDate endDate){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(startDate);
        while(!startDate.equals(endDate)){
            startDate = startDate.plusDays(1);
            dateList.add(startDate);
        }
        return dateList;
    }

    public void exportBusinessData(HttpServletResponse response){
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");

        try{
            fillData(businessDataVO,in,response,dateBegin,dateEnd);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void fillData(BusinessDataVO businessDatavo, InputStream in,
                          HttpServletResponse response,LocalDate dateBegin,LocalDate dateEnd) throws IOException {

        XSSFWorkbook excel = new XSSFWorkbook(in);
        //获取表格文件的Sheet文件
        XSSFSheet sheet = excel.getSheet("Sheet1");
        //填充数据--时间
        sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"至"+dateEnd);
        //获得第4行
        XSSFRow row = sheet.getRow(3);
        row.getCell(2).setCellValue(businessDatavo.getTurnover()); //第3个单元格
        row.getCell(4).setCellValue(businessDatavo.getOrderCompletionRate());
        row.getCell(6).setCellValue(businessDatavo.getNewUsers());
        //获得第5行
        row = sheet.getRow(4);
        row.getCell(2).setCellValue(businessDatavo.getValidOrderCount());
        row.getCell(4).setCellValue(businessDatavo.getUnitPrice());
        //填充明细数据
        for(int i=0;i<30;i++){
            LocalDate date = dateBegin.plusDays(i);
            //查询某一天的营业数据
            businessDatavo = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));
            //获得某一行
            row = sheet.getRow(7+i);
            row.getCell(1).setCellValue(date.toString());
            row.getCell(2).setCellValue(businessDatavo.getTurnover());
            row.getCell(3).setCellValue(businessDatavo.getValidOrderCount());
            row.getCell(4).setCellValue(businessDatavo.getOrderCompletionRate());
            row.getCell(5).setCellValue(businessDatavo.getUnitPrice());
            row.getCell(6).setCellValue(businessDatavo.getNewUsers());
        }
        //3.通过输出流将Excel文件下载到客户端浏览器
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);
        //关闭资源
        out.close();
        excel.close();

    }
}
